<?php
/**
 * 系统公共库文件
 * 主要定义系统公共函数库
 */



/**
 *    获取行为列表显示字段 [名称/类型/用户名称/用户状态]
 *    info:array数组
 *    return Array(名称,类型,用户名称,用户状态)
 */
function getActionMode($info){
    //行为名称
    if( $info['model']=='Menu_add' )  $name = "菜单添加";
    if( $info['model']=='Menu_edit' )  $name = "修改菜单";
    if( $info['model']=='Menu_del' )  $name = "删除菜单";
    if( $info['model']=='Login_login' )  $name = "用户登录";
    if( $info['model']=='Login_logout' )  $name = "用户退出";
    if( $info['model']=='Member_edit' )  $name = "用户信息修改";
    if( $info['model']=='Member_add' )  $name = "添加用户";
    if( $info['model']=='Member_forbiduser' )  $name = "用户禁止登录";
    if( $info['model']=='Member_resumeuser' )  $name = "用户恢复正常";
    if( $info['model']=='Member_deleteuser' )  $name = "用户删除";
    if( $info['model']=='Article_ArticleColumnAdd' )  $name = "添加/编辑文章栏目";
    if( $info['model']=='Article_ArticleColumnDel' )  $name = "删除文章栏目";
    if( $info['model']=='Article_ArticleWrite' )  $name = "添加/编辑文章";
    if( $info['model']=='Article_ArticleDelete' )  $name = "删除文章";
    if( $info['model']=='AuthManager_updateRules' )  $name = "修改权限";
    if( $info['model']=='AuthManager_writeGroup' )  $name = "新建用户组";
    if( $info['model']=='AuthManager_changeStatus' )  $name = "改变用户组状态";
    if( $info['model']=='AuthManager_addToGroup' )  $name = "用户组添加用户";
    if( $info['model']=='AuthManager_removeFromGroup' )  $name = "用户组移出用户";
    if( $info['model']=='AuthManager_addToCategory' )  $name = "用户组添加分类";
    if( $info['model']=='AuthManager_addToModel' )  $name = "用户组添加模型";
    if( $info['model']=='Document_documentsave' )  $name = "上传文档";
    if( $info['model']=='Document_documentdelete' )  $name = "删除文档";
    if( $info['model']=='Virtuallayer_addlayer' )  $name = "添加虚拟图层";
    if( $info['model']=='Virtuallayer_addlayerinfo' )  $name = "添加虚拟图层数据";
    if( $info['model']=='Virtuallayer_dellayerinfo' )  $name = "删除虚拟图层";

    //行为类型
    $typeTmp = explode('_',$info['model']);
    $type = $typeTmp[0];

    //用户名称
    $userInfo = M('member') -> where(array('uid'=>$info['user_id'])) -> find();
    $nickname = $userInfo['nickname'];

    //操作用户的状态
    if( $userInfo['status']==1 )  $status = '正常';
    if( $userInfo['status']==0 )  $status = '禁用';
    if( $userInfo['status']==-1 )  $status = '已删除';

    return array($name, $type, $nickname, $status);
}

/**
 *    迭代排序(从属排序)
 *    param1:列表
 *    param2:参数
 *    return Array 数组内嵌套数组
 */
function flytreeArray($arr, $id = 0, $lev = 1)
{
    $subs = array(); // 子孙数组
    foreach ($arr as $v) {
        if ($v['upid'] == $id) {
            $v['lev'] = $lev;
            $treeArrayInfo = flytreeArray($arr, $v['id'], $lev + 1);
            $v['lists'] = $treeArrayInfo ? $treeArrayInfo : false;
            $subs[] = $v;
        }
    }
    return $subs;
}

/**
 *    迭代排序(从属排序)
 *    param1:列表
 *    param2:参数
 *    return Array 数组不嵌套
 */
function flytree($arr, $id = 0, $lev = 1)
{
    $subs = array(); // 子孙数组
    foreach ($arr as $v) {
        if ($v['upid'] == $id) {
            $v['lev'] = $lev;
            $subs[] = $v; // 举例说找到array('id'=>1,'name'=>'安徽','parent'=>0),
            $subs = array_merge($subs, flytree($arr, $v['id'], $lev + 1));
        }
    }
    return $subs;
}

/*
 * 时间转换
 */
function fdate ($time,$val='Y-m-d H:i:s') {
    if($time)
        return date($val,$time);
    else
        return "";
}

/**
 * 模板中截取使用
 * $str传入字符串（自动去除html标签）
 * $start开始
 * $end结束
 * @return String 返回格式化后的汉字，被截取则 ...后缀
 */
function str_mb_substr($str,$start=0,$end=100,$code='utf-8'){
    $str = trim ($str);
    $str = str_replace (array ('&nbsp;' , '') , '' , $str);
    $str = strip_tags($str);
    $result = mb_substr($str,$start,$end,$code);
    if(mb_strlen($str)>$end) $result .= "...";
    return $result;
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL,$format='Y-m-d H:i'){
    if($time===NULL || $time=="0"){
        $time = time();
        return " ";
    }else{
        $time = intval($time);
        return date($format, $time);
    }
}

/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 */
function is_login(){
    $user = session('user_auth');
    if (empty($user)) {
        return 0;
    } else {
        //单用户登录
        $passport = cookie("user_".md5($user['uid']));
        if($passport==null){
            return 0;
        }
        return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}

/**
 * 检测当前用户是否为管理员
 * @return boolean true-管理员，false-非管理员
 */
function is_administrator($uid = null){
    $uid = is_null($uid) ? is_login() : $uid;
    return $uid && (intval($uid) === C('USER_ADMINISTRATOR'));
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
 * 记录行为日志，并执行该行为的规则
 * @param string $platform 产生该行为的平台，PC、android、IOS
 * @param string $model 触发行为的模型名
 * @param int $record_id 触发行为的记录id
 * @param int $user_id 执行行为的用户id
 * @return boolean
 */
function action_log($platform = null, $model = null, $record_id = null, $user_id = null){

    //参数检查
    if(empty($platform) || empty($model) || empty($record_id)){
        return '参数不能为空';
    }
    if(empty($user_id)){
        $user_id = is_login();
    }

    //插入行为日志
    $data['user_id']        =   $user_id;
    $data['action_ip']      =   ip2long(get_client_ip());
    $data['platform']       =   $platform;
    $data['model']          =   $model;
    $data['record_id']      =   $record_id;
    $data['create_time']    =   time();
    $data['remark']     	=   '操作url：'.$_SERVER['REQUEST_URI'];

    M('ActionLog')->add($data);
}

if(!function_exists('array_column')){
    function array_column(array $input, $columnKey, $indexKey = null) {
        $result = array();
        if (null === $indexKey) {
            if (null === $columnKey) {
                $result = array_values($input);
            } else {
                foreach ($input as $row) {
                    $result[] = $row[$columnKey];
                }
            }
        } else {
            if (null === $columnKey) {
                foreach ($input as $row) {
                    $result[$row[$indexKey]] = $row;
                }
            } else {
                foreach ($input as $row) {
                    $result[$row[$indexKey]] = $row[$columnKey];
                }
            }
        }
        return $result;
    }
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 */
function tree_to_list($tree, $child = '_child', $order='id', &$list = array()){
    if(is_array($tree)) {
        $refer = array();
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if(isset($reffer[$child])){
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby='asc');
    }
    return $list;
}

/**
* 对查询结果集进行排序
* @access public
* @param array $list 查询结果
* @param string $field 排序的字段名
* @param array $sortby 排序类型
* asc正向排序 desc逆向排序 nat自然排序
* @return array
*/
function list_sort_by($list,$field, $sortby='asc') {
   if(is_array($list)){
       $refer = $resultSet = array();
       foreach ($list as $i => $data)
           $refer[$i] = &$data[$field];
       switch ($sortby) {
           case 'asc': // 正向排序
                asort($refer);
                break;
           case 'desc':// 逆向排序
                arsort($refer);
                break;
           case 'nat': // 自然排序
                natcasesort($refer);
                break;
       }
       foreach ( $refer as $key=> $val)
           $resultSet[] = &$list[$key];
       return $resultSet;
   }
   return false;
}

/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string 
 */
function think_ucenter_md5($str, $key = 'ThinkUCenter'){
	return '' === $str ? '' : md5(sha1($str) . $key);
}

/**
 * 动态扩展左侧菜单,base.html里用到
 */
function extra_menu($extra_menu,&$base_menu){
    foreach ($extra_menu as $key=>$group){
        if( isset($base_menu['child'][$key]) ){
            $base_menu['child'][$key] = array_merge( $base_menu['child'][$key], $group);
        }else{
            $base_menu['child'][$key] = $group;
        }
    }
}
/**
 * select返回的数组进行整数映射转换
 *
 * @param array $map  映射关系二维数组  array(
 *                                          '字段名1'=>array(映射关系数组),
 *                                          '字段名2'=>array(映射关系数组),
 *                                           ......
 *                                       )
 * @return array
 *
 *  array(
 *      array('id'=>1,'title'=>'标题','status'=>'1','status_text'=>'正常')
 *      ....
 *  )
 *
 */
function int_to_string(&$data,$map=array('status'=>array(1=>'正常',-1=>'删除',0=>'禁用',2=>'未审核',3=>'草稿'))) {
    if($data === false || $data === null ){
        return $data;
    }
    $data = (array)$data;
    foreach ($data as $key => $row){
        foreach ($map as $col=>$pair){
            if(isset($row[$col]) && isset($pair[$row[$col]])){
                $data[$key][$col.'_text'] = $pair[$row[$col]];
            }
        }
    }
    return $data;
}

/**
 * 根据用户ID获取用户昵称
 * @param  integer $uid 用户ID
 * @return string       用户昵称
 */
function get_nickname($uid = 0){
    static $list;
    if(!($uid && is_numeric($uid))){ //获取当前登录用户名
        return session('user_auth.username');
    }

    /* 获取缓存数据 */
    if(empty($list)){
        $list = S('sys_user_nickname_list');
    }

    /* 查找用户信息 */
    $key = "u{$uid}";
    if(isset($list[$key])){ //已缓存，直接使用
        $name = $list[$key];
    } else { //调用接口获取用户信息
        $info = M('Member')->field('nickname')->find($uid);
        if($info !== false && $info['nickname'] ){
            $nickname = $info['nickname'];
            $name = $list[$key] = $nickname;
            /* 缓存用户 */
            $count = count($list);
            $max   = C('USER_MAX_CACHE');
            while ($count-- > $max) {
                array_shift($list);
            }
            S('sys_user_nickname_list', $list);
        } else {
            $name = '';
        }
    }
    return $name;
}

// 获取数据的状态操作
function show_status_op($status) {
    switch ($status){
        case 0  : return    '启用';     break;
        case 1  : return    '禁用';     break;
        case 2  : return    '审核';       break;
        default : return    false;      break;
    }
}

/**
 * 获取文件真实地址
 * @param int $cover_id
 * @param string $field
 * @return 完整的数据  或者  指定的$field字段值
 */
function get_cover($cover_id, $field = null){
    if(empty($cover_id)){
        return false;
    }
    $file = M('File')->where(array('status'=>1))->getById($cover_id);
	$url = C('PICTURE_UPLOAD.rootPath').$file['savepath'].$file['savename'];
	$url = str_replace('./', '/', $url);
    return empty($field) ? $file : $url;
}
 
/**
 * 面包屑导航
 * @param int $id 当前menu的ID
 */
function get_bread_nav($id){
	if(!empty($id)){
		 $menu = M("Menu");
		 $here = '<ol class="breadcrumb pull-right"><li><a href="'.U('Info/Index/map').'">项目地图</a></li>';
		 $uplevels = $menu->field("id,title,pid,url")->where("id=$id")->find();
		 if($uplevels['pid'] != 0){
			$here .= get_up_levels($uplevels['pid']);
		 }
		 $here .= '<li class = "znavigation2"><a href="'.U($uplevels['url']).'">'.$uplevels['title']."</a></li></ol>";
		 return $here;
	}
}
function get_up_levels($id){
	 $menu = M("Menu");
	 $here = '';
	 $uplevels = $menu->field("id,title,pid,url")->where("id=$id")->find();
	 $here .= '<li class = "znavigation1"><a href="'.U($uplevels['url']).'">'.$uplevels['title']."</a></li>";
	 if($uplevels['pid'] != 0){
	     $here = get_up_levels($uplevels['pid']).$here;
	 }
	 return $here;
}
/**
 * base64_encode 加/解密
 * @param string $str 待加/解密字符;boolean $type 加/解密
 * @return string
 */
function base64($str,$type = true){
    $salt= '/salt moon_@_2017';
    if($type){
        return base64_encode($str.$salt);
    }
    $text = base64_decode($str);
    return strstr($text,$salt,true);
}

/**
 * guid
 * @return string
 */

function getGuid($namespace = '') {
    $guid = '';
    $uid = uniqid("", true);
    $data = $namespace;
    $data .= $_SERVER['REQUEST_TIME'];
    $data .= $_SERVER['HTTP_USER_AGENT'];
    $data .= $_SERVER['LOCAL_ADDR'];
    $data .= $_SERVER['LOCAL_PORT'];
    $data .= $_SERVER['REMOTE_ADDR'];
    $data .= $_SERVER['REMOTE_PORT'];
    $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
    $guid = substr($hash,  0,  8) .
                '-' .
                substr($hash,  8,  4) .
                '-' .
                substr($hash, 12,  4) .
                '-' .
                substr($hash, 16,  4) .
                '-' .
                substr($hash, 20, 12);
    return $guid;
}